<template>
  <div>
     <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card shadow="hover">
      <el-row>
        <el-col><el-button @click="dialogVisible=true" type="primary">添加角色</el-button></el-col>
      </el-row>
    </el-card>
    <!-- 角色列表区域 -->
     <el-table :data="rolesList" stripe style="width: 100%">
       <!-- 展开列 -->
      <el-table-column type="expand" label="#">
        <template v-slot="{row}">
          <el-row :class="['border-bottom',index1===0?'border-top':'','vcenter']"v-for="(item,index1) in row.children" :key="item.id">
            <!-- 渲染一级权限 -->
            <el-col :span="5">
              <el-tag closable @close="removeRightById(row,item.id)">{{item.authName}}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 渲染其他权限 -->
            <el-col :span="19">
              <!-- 渲染二级权限 通过v-for一级权限.children -->
              <el-row :class="[index2===0? '':'border-top','vcenter']" v-for="(item2,index2) in item.children" :key="item2.id">
                <el-col :span="6">
                  <el-tag type="success" closable @close="removeRightById(row,item2.id)"  >{{item2.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 渲染三级权限 -->
                <el-col :span="18">
                  <el-row v-for="(item3,index3) in item2.children" :key="item3.id">
                    <el-tag type="warning" closable @close="removeRightById(row,item3.id)">{{item3.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-row>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column type="index" label="#"></el-table-column>
      <el-table-column prop="roleName" label="角色名称"></el-table-column>
      <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
      <el-table-column label="操作">
        <template v-slot="{row}">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="editRole(row.id)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRole(row.id)">删除</el-button>
          <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRights(row)">分配权限</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加角色对话框区域 -->
    <el-dialog title="添加角色" :visible.sync="dialogVisible" @close="addRolesClose">
      <el-form :model="addRoleData" :rules="addRoleRules" label-width="80px" ref="addRolesFormRef">
        <el-form-item label="角色ID" prop="roleId" >
          <el-input v-model="addRoleData.roleId" ></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleData.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleData.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑角色对话框区域 -->
    <el-dialog title="编辑角色" :visible.sync="editDialogVisible">
      <el-form :model="editRoleData" :rules="editRoleRules" label-width="80px" ref="editRolesFormRef">
        <el-form-item label="角色ID" prop="roleId" >
          <el-input v-model="editRoleData.roleId" ></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName" >
          <el-input v-model="editRoleData.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleData.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleBtn">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配权限对话框区域 -->
    <el-dialog
      title="提示"
      :visible.sync="setRightDialogVisible"
      width="40%" @close="closeRightDialog">
      <!-- 树形控件 -->
      <el-tree :data="rightsBaseList" ref="RightsTreeRef" :props="RightsTreeProps " show-checkbox node-key="id" :default-expand-all="true" :default-checked-keys="dfKeys"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="assignRights">确 定</el-button>
      </span>
    </el-dialog>
    

  </div>
</template>
<script>
import {getRolesList,AddRolesReq,editRoleReq,changeRoleInfoReq,deleteRoleInfoReq,deleteRoleRightReq,setRightsReq,assignRightsReq} from '../../networks/power'
export default {
  name:'Roles',
  data() {
    var checkId=(rule,value,callback)=>{
      var regId=/^\d{1,}$/;
      if(regId.test(value)){
        return callback();
      }else{
        callback(new Error("id 必须是数字！"))
      }
    }
    return {
      rolesList:[],
      //控制对话框的显示与隐藏
      dialogVisible:false,
      //对话框中表单的数据对象
      addRoleData:{
        roleId: "",
        roleName: "",
        roleDesc: ""
      },
      //对话框中表单的规则对象
      addRoleRules:{
        roleId:[
          { required: true, message: '请输入角色id', trigger: 'blur' },
          { validator:checkId, trigger: 'blur' }],
        roleName:[
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }],
        roleDesc:[
          { required: true, message: '请输入角色描述信息', trigger: 'blur' }]

      },
      //控制编辑对话框的显示与隐藏
      editDialogVisible:false,
      // 编辑对话框的form数据对象，由请求过来的数据渲染出来
      editRoleData:{},
      // form的规则对象
      editRoleRules:{
         roleName:[
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        roleDesc:[
          { required: true, message: '请输入角色描述信息', trigger: 'blur' },
        ]
      },
      //设置权限对话框的显示与隐藏
      setRightDialogVisible:false,
      // 分配权限列表
      rightsBaseList:[],
      //树形控件对应的分层属性
      RightsTreeProps:{
        // 控制嵌套的属性
        children: 'children',
        //控制显示的文本
        label: 'authName'
      },
      //存放要选中的节点的id
      dfKeys:[],
      //存放发送设置权限请求时的id
      roleIdReq:'',
    }
  },
  created() {
    //请求角色列表数据
    this.getRolesListInfo()
  },
  methods: {
    //请求角色列表数据
    getRolesListInfo(){
      getRolesList().then(res=>{
        // console.log(res);
        if(res.meta.status!==200) return this.$message.error(res.meta.msg)
        //保存数据
        this.rolesList=res.data;
        console.log(this.rolesList,'rolelist');

      })
    },
    //监听对话框的关闭，然后重置表单数据
    addRolesClose(){
      this.$refs.addRolesFormRef.resetFields();
    },
    //监听对话框确定按钮的点击
    addRoles(){
      //首先与验证
      this.$refs.addRolesFormRef.validate(valid=>{
        console.log(valid);
        //valid为boolean
        if(!valid) return ;
        //发送添加角色的请求
        AddRolesReq(this.addRoleData).then(res=>{
          if(res.meta.status!==201) return this.$message.error(res.meta.msg);
          //添加角色成功后要提示用户，刷新角色列表，然后关闭对话框
          this.$message.success("添加角色成功！");
          this.getRolesListInfo();
          this.dialogVisible=false;

        })
      })
    },
    //监听操作里面的编辑按钮
    editRole(id){
      console.log(id);
      console.log(typeof id);
      //显示编辑对话框
      this.editDialogVisible=true;
      //拿到id,去请求角色的数据，然后渲染到对话框里
      editRoleReq("roles/"+id).then(res=>{
        console.log(res,"role");
        this.editRoleData=res.data;
      })
    },
    //监听确定的点击事件，然后预验证
    editRoleBtn(){
      this.$refs.editRolesFormRef.validate(valid=>{
        console.log(valid);
        if(!valid) return;
        console.log(this.editRoleData);
        //发送修改角色的请求 带name和desc 参数
        const result =changeRoleInfoReq("roles/"+this.editRoleData.roleId,
          {roleName:this.editRoleData.roleName,roleDesc:this.editRoleData.roleDesc});
        result.then(res=>{
          console.log(res,"edit");
          if(res.meta.status!==200) return this.$message.error(res.meta.msg);
          //获取成功后更新角色信息列表，提示添加成功，关闭对话框
          this.getRolesListInfo();
          this.$message.success("编辑角色信息成功！")
          this.editDialogVisible=false;
        })
      })
    },
    //监听操作里面的删除按钮
    deleteRole(id){
      //弹出警告弹框
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(res=>{
          console.log(res);
          //执行confirm，删除用户的角色
          console.log("delete",id);
          deleteRoleInfoReq("roles/"+id).then(res=>{
            // console.log("delete",res);
            if(res.meta.status!==200) return this.$message.error(res.meta.msg);
            //更新数据 提示成功
            this.getRolesListInfo();
            this.$message.success("删除成功！")

          })

        }).catch(err=>{
          console.log(err);
          //执行cancel
          this.$message.info("取消删除！")
        })
    },
    //删除权限提供角色id和权限的id
    removeRightById(role,rightId){
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res=>{
        console.log(res);
        // 发起请求
        deleteRoleRightReq(`roles/${role.id}/rights/${rightId}`).then(res=>{
          console.log("删除",res);
          if(res.meta.status!==200) return this.$message.error(res.meta.msg);
          //提醒用户删除权成功，冲i性能复制权限
          role.children=res.data;
        })
      }).catch(err=>{
        console.log(err);
      })
    },
    //设置分配权限
    setRights(role){
      console.log(role.id,"setRights1");
      this.roleIdReq=role.id;

      console.log(this.roleIdReq,"setRights");
      //获取三级节点id
      this.getLeafKeys(role,this.dfKeys);
      //弹出设置权限对话框
      this.setRightDialogVisible=true;
      //请求数据
      setRightsReq().then(res=>{
        console.log(res,"rights");
        if(res.meta.status!==200) return this.$message.error(res.meta.msg);
        //成功后保存数据
        this.rightsBaseList=res.data;
        console.log(this.rightsBaseList);
      })


    },
    //通过递归  获取三层权限所有id,并保存到dfKeys
    getLeafKeys(node,arr){
      if(!node.children){
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item,arr)
        
      });
    },
    //监听对话框关闭，将保存权限id的数组清空
    closeRightDialog(){
      this.dfKeys=[];
    },
    //监听确定按钮的点击事件
    assignRights(){
     //拿到被勾选的和半勾选的节点的id,使用树形组件的方法
      const checkedNodeId=[ ...this.$refs.RightsTreeRef.getCheckedKeys(),
       ...this.$refs.RightsTreeRef.getHalfCheckedKeys()];
      // 拿到节点后要发起请求，分配权限
      const checkedNodeIdStr=checkedNodeId.join(",");
      // console.log(checkedNodeIdStr);
      // console.log(this.roleIdReq,"assignRightsReq==id");
      assignRightsReq(`roles/${this.roleIdReq}/rights`,{rids:checkedNodeIdStr}).then(res=>{
        // console.log(res,"assignRightsReq");
        if(res.meta.status!==200) return this.$message.error("分配权限失败！");
        //成功 通知，然后刷新列表，关闭对话框
        this.$message.success("分配权限成功！")
        this.getRolesListInfo();
        this.setRightDialogVisible=false;

      })
       
      
    }
    
  },
}
</script>
<style scoped>
.el-tag{
  margin:7px;
}
.border-bottom{
  border-bottom: 1px solid #eee;
}
.border-top{
  border-top:1px solid #eee;
}
.vcenter{
  display: flex;
  align-items: center;
}
  

</style>